﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace mKoenig.PictureSlide
{
  static class Program
  {
    /// <summary>
    /// Der Haupteinstiegspunkt für die Anwendung.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
      string argPrefix;
      int argHandle;

      if (args.Length > 2)
      {
        MessageBox.Show("Too many arguments on the command line.");
        return;
      }

      ParseArgsToPrefixAndArgInt(args, out argPrefix, out argHandle);

      try
      {
        switch (argPrefix)
        {
          case "/a": // password dialog desired. 
            break;
          case "/c":
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Setup());
            break;
          case "/p":
            if (argHandle != 0)
            {
              Minipreview mini = new Minipreview();
              mini.DoMiniPreview(argHandle);
              mini = null;
            }
            else
            {
              TestPreview test = new TestPreview();
              test.Show();

              Minipreview mini = new Minipreview();
              mini.DoMiniPreview((int)test.Handle);
              mini = null;
            }
            //else
            //  goto case "/s"; // No handle found, do a fullscreen screensaver.
            break;
          case "/s":
            Screensaver saver = new Screensaver();
            saver.RunMe();
            saver = null;
            break;
          default:
            break;
        }
      }

#if DEBUG
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
#else
      catch
      {
        // Just exit because this is a screensaver for unattended operation. We don't want a message
        // and we want to exit if anything goes wrong.
      }
#endif
    }

    private static void ParseArgsToPrefixAndArgInt(string[] args, out string argPrefix, out int argHandle)
    {
      string curArg;
      char[] SpacesOrColons = { ' ', ':' };

      switch (args.Length)
      {
        case 0: // Nothing on command line, so just start the screensaver.
          argPrefix = "/c";
          argHandle = 0;
          break;
        case 1:
          curArg = args[0];
          argPrefix = curArg.Substring(0, 2);
          curArg = curArg.Replace(argPrefix, ""); // Drop the slash /? part.
          curArg = curArg.Trim(SpacesOrColons); // Remove colons and spaces.
          argHandle = curArg == "" ? 0 : int.Parse(curArg); // if empty return zero. else get handle.
          break;
        case 2:
          argPrefix = args[0].Substring(0, 2);
          argHandle = int.Parse(args[1].ToString());
          break;
        default:
          argHandle = 0;
          argPrefix = "";
          break;
      }
    }
  }
}
